package com.wrupple.muba.catalogs.client.module.services.logic.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.vegetate.client.VegetateClientException;
import com.wrupple.vegetate.domain.CatalogResponseContract;

public class CatalogVegetateChannelTransitionWrapper extends
		DataCallback<CatalogResponseContract> {
	StateTransition<List<CatalogEntry>> wrapped;
	private String catalogid;

	public CatalogVegetateChannelTransitionWrapper(
			StateTransition<List<CatalogEntry>> wrapped, String catalogid) {
		super();
		this.wrapped = wrapped;
		this.catalogid = catalogid;
	}
	
	@Override
	public void execute() {
		if (result.getResponse() == null) {
			GWT.log("Received empty response");
			wrapped.setResultAndFinish(null);
			if (result.getError() == null) {
				
			} else {
				throw new VegetateClientException(result.getError(), new RuntimeException(
						result.getError()));
			}
		} else {
			List<CatalogEntry> returnList = (List<CatalogEntry>) result.getResponse();
			ArrayList<CatalogEntry> list = new ArrayList<CatalogEntry>(
					returnList.size());
			for(CatalogEntry e : returnList){
				if(e==null){
					GWT.log("null entry found and removed from response, wtf?");
				}else{
					setCatalog(e, catalogid);
					list.add(e);
				}
			}
			
			wrapped.setResultAndFinish(list);
		}
		
	}
	protected static final native void setCatalog(JavaScriptObject entry,
			String id) /*-{
		entry["catalog"] = id;
	}-*/;

}
